﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// 在文件顶部添加对login类的引用
using Mes;
using System.Net.Http;

namespace Mes.采购管理
{
    public partial class Approval : Form
    {
        private string purchaseNo; // 采购编号

        // 审批人类，用于存储ID和名称
        private class Approver
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        private class Result
        {
            public string Name { get; set; }
        }
        public Approval(string purchaseNo)
        {
            InitializeComponent();
            this.purchaseNo = purchaseNo;
        }

        private void Approval_Load(object sender, EventArgs e)
        {
            // 设置窗口状态为正常
            this.WindowState = FormWindowState.Normal;
            Console.WriteLine("窗体加载完成");


            // 添加审批人数据
            List<Approver> approvers = new List<Approver>
            {
                new Approver { Id = 1, Name = "张三" },
                new Approver { Id = 2, Name = "王五" },
                new Approver { Id = 3, Name = "李四" }
            };
            // 添加审批人数据
            List<Result> result = new List<Result>
            {
                new Result {  Name = "通过" },
                new Result { Name = "驳回" },
            };
            // 绑定数据到下拉框
            comApprover.DataSource = approvers;
            comApprover.DisplayMember = "Name"; // 显示名称
            comApprover.ValueMember = "Id";     // 实际值为ID
            comApprover.SelectedIndex = 0;      // 设置默认选中项
            comResult.DataSource = result;
            comResult.DisplayMember = "Name"; // 显示名称
            comResult.ValueMember = "Name";     // 实际值为ID
            comResult.SelectedIndex = 0;      // 设置默认选中项

            // 添加单选按钮事件处理
            radioIs_Final1.CheckedChanged += new EventHandler(radioIs_Final_CheckedChanged);
            radioIs_Final2.CheckedChanged += new EventHandler(radioIs_Final_CheckedChanged);

            // 初始设置下拉框可见性
            UpdateApproverComboBoxVisibility();
        }

        // 单选按钮事件处理方法
        private void radioIs_Final_CheckedChanged(object sender, EventArgs e)
        {
            UpdateApproverComboBoxVisibility();
        }

        // 更新下拉框可见性的方法
        private void UpdateApproverComboBoxVisibility()
        {
            // 如果选择"是"(结束流程)，则隐藏下拉框
            // 如果选择"否"(不结束流程)，则显示下拉框
            comApprover.Visible = radioIs_Final2.Checked;
            // 同时隐藏/显示标签
            Request_Ddte.Visible = radioIs_Final2.Checked;
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var approvalData = new
            {
                Reqest_No = purchaseNo,
                Result = comResult.SelectedValue?.ToString() ?? "",
                Comment = textComment.Text,
                Is_Final = !radioIs_Final1.Checked,  // 是(结束流程)->true，否(不结束流程)->false
                Approver_Ddte = radioIs_Final1.Checked ? 0 : (int?)comApprover.SelectedValue,  // 是(结束流程)->0，否(不结束流程)->选中的审批人ID
                command = "Approve"
            };
            
            try
            {
                string json = JsonConvert.SerializeObject(approvalData);
                string apiUrl = "http://10.223.8.9:8082/api/Purchase/ApprovePurchase";
                
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }
            
                    // 创建请求内容
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string responseText = await response.Content.ReadAsStringAsync();
                    
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("采购申请添加成功！");
                        // 清空表单
                        ClearForm();
                    
                        // 刷新采购列表页面
                        bool isRefreshed = false;
                        foreach (Form form in Application.OpenForms)
                        {
                            if (form is Purchaseshow purchaseshowForm)
                            {
                                purchaseshowForm.RefreshData();
                                isRefreshed = true;
                                break;
                            }
                        }
                    
                        if (!isRefreshed)
                        {
                            MessageBox.Show("采购申请添加成功，但未找到采购列表页面。");
                        }
                    
                        // 关闭当前添加页面
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show($"添加失败，HTTP 状态码：{(int)response.StatusCode}, 错误信息：{responseText}");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string errorText = "未知错误";
                int statusCode = 0;
                string errorType = "网络请求错误";
                
                if (ex.Message.Contains("40"))
                {
                    errorType = "客户端错误";
                }
                else if (ex.Message.Contains("50"))
                {
                    errorType = "服务器错误";
                }
                else if (ex.Message.Contains("Connect"))
                {
                    errorType = "连接失败";
                    errorText = "无法连接到服务器，请检查网络连接或服务器状态。";
                }
                else if (ex.Message.Contains("timeout"))
                {
                    errorType = "请求超时";
                    errorText = "请求超时，请稍后再试。";
                }
                
                ShowError($"添加失败：{errorType}\n错误信息：{ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
            }
        }
        private void ClearForm()
        {
            textComment.Text = "";
            comApprover.SelectedIndex = -1; // 重置原料下拉框
        }
        // 添加统一的错误提示方法
        private void ShowError(string message)
        {
            MessageBox.Show(message, "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

}
